package yunhe.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import yunhe.biz.SupBiz;
import yunhe.entity.Product;
import yunhe.entity.Supplier;


@WebServlet(name="SupServlet",urlPatterns="/SupplierServlet")
public class SupplierServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		SupBiz supBiz=new SupBiz();
		//当前页(字符串)
		String pageIndex=req.getParameter("pageIndex");
		if(pageIndex==null){
			pageIndex="1";
		}
		//当前页（转换int）
		int curPage=Integer.parseInt(pageIndex);
		//总条数
		int supCount=supBiz.getSupCount();
		//每页显示行数
		int pageSize=10;
		//页数
		int totalPages=supCount%pageSize==0?supCount/pageSize:supCount/pageSize+1;
				
		if(curPage<1){
			curPage=1;
		}else if(curPage>totalPages){
			curPage=totalPages;
		}
		String search=req.getParameter("search");
		String searchText=req.getParameter("searchText");
		HashMap<String,String> searchMap=new HashMap<>();
		searchMap.put("search", search);
		searchMap.put("searchText", searchText);
		ArrayList<Supplier> supList=supBiz.getAllSup(searchMap);
		
		JSONArray jsonArray=new JSONArray();
		if(!supList.isEmpty()){
	         for (int i=0;i<supList.size();i++){
	             Map<String,String> mss=new HashMap<String,String>();
	             mss.put("supId",supList.get(i).getSupId());
	             mss.put("supName",supList.get(i).getSupName());
	             mss.put("supLinkMan",supList.get(i).getSupLinkMan());
	             mss.put("supTel",supList.get(i).getSupTel());
	             mss.put("supAddr",supList.get(i).getSupAddr());
	             mss.put("supEmail",supList.get(i).getSupEmail());
	             mss.put("supBank",supList.get(i).getSupBank());
	             mss.put("supAccount",supList.get(i).getSupAccount());
	             mss.put("supTaxNum",supList.get(i).getSupTaxNum());
	             jsonArray.put(mss);
	         }
	     }
		String str="{\"total\":"+supCount+",\"rows\":"+jsonArray.toString()+"}";
		resp.getWriter().print(str);
		
		
//		req.setAttribute("supList", supList);
//		req.setAttribute("curPage", curPage);
//		req.setAttribute("totalPages", totalPages);
//		req.getRequestDispatcher("/FileMgr/SupplierFile.jsp").forward(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
